<script setup lang="ts">
import type { PropType } from 'vue';
import { nextTick, ref, watch } from 'vue';
import { ElButton } from 'element-plus';
import { questionTypeOptions } from '../const';
import { useCourseChapter } from './question-hook';
import Drawer from './drawer.vue';
import UploadModal from './upload-modal.vue';

defineOptions({ name: 'Query' });

interface ModelValueType {
  type: string[];
  stem: string;
  courseId?: string;
  chapterId?: string;
}

const props = defineProps({
  modelValue: {
    type: Object as PropType<ModelValueType>,
    required: true,
  },
});

const emit = defineEmits(['update:modelValue', 'queryData', 'toggleAllCards']);

// 使用共享的课程章节 hooks
const {
  courseOptions,
  chapterOptions,
  courseLoading,
  chapterLoading,
  getCourseInfo,
  handleCourseChange
} = useCourseChapter();

// 创建本地响应式数据副本，避免直接修改props
const localQueryData = ref<ModelValueType>({
  type: [],
  stem: '',
  courseId: '',
  chapterId: ''
});

// 同步props到本地数据
watch(() => props.modelValue, (newValue) => {
  localQueryData.value = { ...newValue };
}, { immediate: true, deep: true });

// 同步本地数据到props
watch(localQueryData, (newValue) => {
  emit('update:modelValue', { ...newValue });
}, { deep: true });

// 组件引用
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null);
const uploadModalRef = ref<InstanceType<typeof UploadModal> | null>(null);
const isCollapsed = ref(false);

// 初始化时获取课程信息
getCourseInfo();

// 监听课程ID变化，自动获取章节信息
watch(() => localQueryData.value.courseId, (newCourseId, oldCourseId) => {
  handleCourseChange(newCourseId || '');
  localQueryData.value.chapterId = '';
});

// 事件处理函数
const handleReset = () => {
  // emit('queryData');
  localQueryData.value = { type: [], stem: '', courseId: '', chapterId: '' };
  nextTick(() => {
    emit('queryData');
  })
};

const handleSearch = () => {
  emit('queryData');
};

const handleToggleAllCards = () => {
  isCollapsed.value = !isCollapsed.value;
  emit('toggleAllCards', isCollapsed.value);
};

const handleOpenUploadModal = () => {
  uploadModalRef.value?.open();
};

// 抽屉相关操作
const onAdd = () => {
  drawerRef.value?.init();
};

const onEdit = () => {
  drawerRef.value?.init();
};

defineExpose({
  onEdit,
});

</script>
<template>
  <div class="query flex justify-between bg-[#fff] pb-[15px] px-[24px] pt-[24px] flex-col">
    <div class="w-full flex items-center justify-between">
      <base-query :columns="[
        {
          prop: 'type',
          label: $t('questionBank.questionType'),
          type: 'select',
          multiple: true,
          options: questionTypeOptions,
          placeholder: $t('common.selectPhTxt', [$t('questionBank.questionType')]),
        },
        {
          prop: 'courseId',
          label: $t('exam.courseNameTxt'),
          placeholder: $t('common.selectPhTxt', [$t('exam.courseNameTxt')]),
          options: courseOptions,
        },
        {
          prop: 'chapterId',
          label: $t('course.chapter'),
          placeholder: $t('common.selectPhTxt', [$t('course.chapter')]),
          options: chapterOptions,
        },
        {
          prop: 'stem',
          label: $t('questionBank.question'),
          type: 'input',
          placeholder: $t('common.inputPhTxt', [$t('questionBank.question') + '名称']),
        },
      ]" :data="localQueryData" @reset="handleReset" @click="handleSearch" label-position="right" />
    </div>
    <el-divider class="my-0 mb-4" />
    <div class="more flex">
      <div class="w-full flex items-center">
        <ElButton type="primary" @click="onAdd">{{ $t('questionBank.add') }}</ElButton>
        <ElButton plain class="mr-[10px]" @click="handleOpenUploadModal">{{ $t('questionBank.import') }}
        </ElButton>
      </div>
      <el-button type="primary" link class="ml-auto" @click="handleToggleAllCards">
        {{ isCollapsed ? $t('questionBank.expandAll') : $t('questionBank.collapseAll') }}
      </el-button>
    </div>
    <Drawer ref="drawerRef" @query-data="handleSearch" />
    <UploadModal ref="uploadModalRef" @refresh="handleSearch" />
  </div>
</template>
<style lang="less" scoped>
.search:hover {
  color: var(--el-color-primary);
}
</style>
